package org.ithang.tools.timer;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ithang.application.btRecord.bean.BtRecord;
import org.ithang.application.btRecord.service.BtRecordService;
import org.ithang.system.keyvalue.bean.Keyvalue;
import org.ithang.system.keyvalue.service.KeyvalueService;
import org.ithang.system.sysLog.bean.SysLog;
import org.ithang.system.sysLog.service.SysLogService;
import org.ithang.tools.eth.ETHInfo;
import org.ithang.tools.eth.ETHUtil;
import org.ithang.tools.lang.DateUtils;
import org.ithang.tools.lang.JsonUtils;
import org.ithang.tools.lang.StrUtils;
import org.ithang.tools.model.ErrorInfo;
import org.ithang.tools.redis.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;


/**
 * 发矿工费
 * @author zyt
 *
 */
@JobHandler(value="grantkHandler")
@Component
public class GrantkHandler extends IJobHandler {

	@Autowired
	private BtRecordService btRecordService;
	
	@Autowired
	private KeyvalueService keyvalueService;
	
	@Autowired
	private SysLogService sysLogService;
	
	@Override
	public ReturnT<String> execute(String param) throws Exception {
		XxlJobLogger.log("开始发矿工费");
		
		try{
			   
			Keyvalue gas=keyvalueService.get(Keys.Gas);
			if(null==gas||gas.doubleValue()<=0){
				return FAIL;
			}
			
			
			Keyvalue gasBalance=keyvalueService.get(Keys.GasBalance);
			
			Thread gasThread=new Thread(new Runnable(){
				@Override
				public void run() {
                    try{
					//发gas
					List<String> addrs=keyvalueService.listsStr("select addr from bc_addr");
					

					boolean test=false;
						    Keyvalue kv=keyvalueService.get(Keys.TestDev);
						    if(null!=kv&&1==kv.intValue()){
						    	test=true;
						    }
					
					for(String addr:addrs){
						try{
							double balance=ETHUtil.getTokenBalance(addr,test);
							
							if(balance>=gasBalance.doubleValue()){
								ETHInfo info=ETHUtil.transferETH(StrUtils.dhx(keyvalueService.getKPrikey()), addr, gas.doubleValue());
								 if(null!=info){
								    	SysLog log=new SysLog();
								    	log.setSlog(JsonUtils.toJsonStr(info));
								    	log.setCtime(DateUtils.getSystime());
								    	sysLogService.add(log);
								  }
							}
						}catch(Exception e){
							e.printStackTrace();
							SysLog log=new SysLog();
					    	log.setSlog(e.getMessage());
					    	log.setCtime(DateUtils.getSystime());
					    	sysLogService.add(log);
						}
					}
                    }catch(Exception e){
                    	e.printStackTrace();
                    }
                    
				}
			});
			gasThread.start();
			
		}catch(Exception e){
			e.printStackTrace();
			return FAIL;
		}
		
		
		return SUCCESS;
	}

}
